from rest_framework import serializers

from goods.models import SKU


class CartSerializers(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)
    count = serializers.IntegerField(min_value=1)
    selected = serializers.BooleanField(default=True)
    # 判断商品和库存
    def validate(self, attrs):
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')
        if attrs['count'] > sku.stock:
            raise serializers.ValidationError('库存不足')
        return attrs

class CartDeleteSerializers(serializers.Serializer):
    sku_id = serializers.IntegerField(min_value=1)

    # 判断商品和库存
    def validate(self, attrs):
        try:
            sku = SKU.objects.get(id=attrs['sku_id'])
        except:
            raise serializers.ValidationError('商品不存在')

        return attrs

class CartSelectedSerializers(serializers.Serializer):
    selected = serializers.BooleanField()

class SKUSerializers(serializers.ModelSerializer):
    count = serializers.IntegerField(read_only=True)
    selected = serializers.BooleanField(read_only=True)
    class Meta:
        model = SKU
        fields = '__all__'
